package com.banciyuan.bcywebview.biz.event;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.View;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.api.EventApi;
import com.banciyuan.bcywebview.api.IllustApi;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreashRecycleView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.post.RulesDialog;
import com.banciyuan.bcywebview.biz.post.StartPostActivity;
import com.banciyuan.bcywebview.biz.post.cos.CosPostActivity;
import com.banciyuan.bcywebview.biz.post.illust.illustPostActivity;
import com.banciyuan.bcywebview.biz.post.rule.RuleHelper;
import com.banciyuan.bcywebview.biz.post.rule.SimpleRuleImpl;
import com.banciyuan.bcywebview.biz.post.write.PostWriteDialog;
import com.banciyuan.bcywebview.biz.post.write.WriteArticleActivity;
import com.banciyuan.bcywebview.biz.post.write.series.SelectSeriesActivity;
import com.banciyuan.bcywebview.biz.share.ShareActivity;
import com.banciyuan.bcywebview.biz.write.write.WriteActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Card;
import de.greenrobot.daoexample.model.Event;
import de.greenrobot.daoexample.model.PostRule;
import de.greenrobot.daoexample.model.Rules;
import de.greenrobot.daoexample.model.TagDetail;


public class EventDetailActivity extends BaseActivity implements ActionbarHelper.OnActionCallbacks, View.OnClickListener {
    protected String event_id;
    private Event event;
    private RequestQueue mQueue;
    private PullToRefreashRecycleView mRefreshLv;
    private RecyclerView mRecyclerView;
    private GridLayoutManager mGridLayoutManager;
    private ProgressbarHelper mProgressbarHelper;
    private EventDetailAdapter mEventDetailAdapter;
    private int page = 1;
    private String mType;
    private List<Card> mCardList = new ArrayList<>();
    private boolean loading = false;
    private boolean end_flag = false;
    private String event_order = "hot";
    private PostRule postRule;
    private RulesDialog rulesDialog;
    private View viewLoading;
    private View viewTopIndicator;
    private int header_height;
    private View hotIndicator;
    private View updateIndicator;
    private View tvUpdateTimeTips;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.event_detail_layout);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
        event_id = getIntent().getStringExtra(gotoUtil.INTENT_VALUE_ONE);
    }

    @Override
    protected void initProgressbar() {
        View mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        View mActionBarView = findViewById(R.id.base_action_bar);
        ActionbarHelper mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.event_detial));
        mActionbarHelper.setActionCallbacks(this);
        mActionbarHelper.addOneAction(R.drawable.share_black);
    }

    @Override
    protected void initUi() {
        viewLoading = findViewById(R.id.pb_loading);
        initViewTopIndicator();
        mRefreshLv = (PullToRefreashRecycleView) findViewById(R.id.event_refresh_rv);
        mRecyclerView = mRefreshLv.getRefreshableView();
        mGridLayoutManager = new GridLayoutManager(this, 2);
        RecyclerView.ItemAnimator animator = mRecyclerView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        mGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch (mEventDetailAdapter.getItemViewType(position)) {
                    case EventDetailAdapter.HEADER_TYPE:
                        return 2;
                    default:
                        return 1;
                }
            }
        });
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int type = parent.getAdapter().getItemViewType(parent.getChildAdapterPosition(view));
                int index = parent.getChildAdapterPosition(view) % 2;
                if (type != EventDetailAdapter.HEADER_TYPE) {
                    if (index == 0) {
                        outRect.right = UIUtils.dip2px(16, EventDetailActivity.this);
                        outRect.left = UIUtils.dip2px(4, EventDetailActivity.this);
                    } else {
                        outRect.right = UIUtils.dip2px(4, EventDetailActivity.this);
                        outRect.left = UIUtils.dip2px(16, EventDetailActivity.this);
                    }
                }
            }

            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                c.drawColor(getResources().getColor(R.color.white));
            }
        });
        mRecyclerView.setLayoutManager(mGridLayoutManager);
        mEventDetailAdapter = new EventDetailAdapter(this, mCardList);
        mRecyclerView.setAdapter(mEventDetailAdapter);
    }

    private void initViewTopIndicator() {
        viewTopIndicator = findViewById(R.id.event_header_top_indicator);
        hotIndicator = viewTopIndicator.findViewById(R.id.hot_indicator);
        updateIndicator = viewTopIndicator.findViewById(R.id.update_indicator);
        tvUpdateTimeTips = viewTopIndicator.findViewById(R.id.tv_update_tiem_tips);
        viewTopIndicator.findViewById(R.id.view_sort_by_hot).setOnClickListener(this);
        viewTopIndicator.findViewById(R.id.view_sort_by_update).setOnClickListener(this);
    }

    @Override
    protected void initAction() {
        mRefreshLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
            @Override
            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                if (!loading) {
                    loading = true;
                    end_flag = false;
                    page = 1;
                    initData();
                }
            }
        });

        mRecyclerView.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onBottom() {
                if (!end_flag && !loading) {
                    loading = true;
                    page++;
                    getHotData();
                }
            }

            @Override
            public void showPostion(int firstVisibleItem) {
                View firstChild = mRecyclerView.getChildAt(0);
                if (null != firstChild) {
                    header_height = firstChild.getMeasuredHeight();
                    int height = Math.abs(firstChild.getTop()) + UIUtils.dip2px(54, EventDetailActivity.this);
                    if (viewTopIndicator.getVisibility() == View.GONE && header_height != 0 && firstVisibleItem == 0 && height >= header_height) {
                        viewTopIndicator.setVisibility(View.VISIBLE);
                    } else if (viewTopIndicator.getVisibility() == View.VISIBLE && header_height != 0 && firstVisibleItem == 0 && height < header_height) {
                        viewTopIndicator.setVisibility(View.GONE);
                    } else if (firstVisibleItem >= 1 && viewTopIndicator.getVisibility() == View.GONE) {
                        viewTopIndicator.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {
        getDetail();
        getHotData();
    }

    private void getHotData() {
        String url = HttpUtils.BASE_URL + EventApi.getListposts();
        List<BcyPair> BcyPairList = new ArrayList<>();
        BcyPairList.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        BcyPairList.add(new BcyPair(HttpUtils.EVENT_ID, event_id));
        BcyPairList.add(new BcyPair(HttpUtils.ORDER, event_order));
        Map<String, String> map = HttpUtils.getData(BcyPairList);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, EventDetailActivity.this)) {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        mType = jsonObject1.getString("type");
                        boolean isDingStart = jsonObject1.optBoolean("ding_st");
                        JSONArray jsonArray = jsonObject1.getJSONArray("rp_data");
                        Gson gson = new Gson();
                        List<Card> templist = gson.fromJson(jsonArray.toString(), new TypeToken<List<Card>>() {
                        }.getType());
                        for (Card card : templist) {
                            card.setDingStart(isDingStart);
                            if (!TextUtils.isEmpty(card.getWork()))
                                card.getPost_tags().add(0, new TagDetail(card.getWid(), card.getWork(), card.getWork()));
                        }
                        if (templist.isEmpty())
                            end_flag = true;
                        dealCardData(templist);
                        onSucc();
                    } else {
                        onError();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onError();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                onError();
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, this, map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        mQueue.add(requestParam);
    }

    private void onSucc() {
        mProgressbarHelper.onSuccess();
        mRefreshLv.onRefreshComplete();
        viewLoading.setVisibility(View.GONE);
        loading = false;
    }

    private void onError() {
        mProgressbarHelper.onFailed();
        mRefreshLv.onRefreshComplete();
        viewLoading.setVisibility(View.GONE);
        loading = false;
    }

    private void getDetail() {
        String url = HttpUtils.BASE_URL + EventApi.getDetail();
        List<BcyPair> BcyPairList = new ArrayList<>();
        BcyPairList.add(new BcyPair(HttpUtils.EVENT_ID, event_id));
        Map<String, String> map = HttpUtils.getData(BcyPairList);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, EventDetailActivity.this)) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject jsonObject1 = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        event = gson.fromJson(jsonObject1.toString(), new TypeToken<Event>() {
                        }.getType());
                        processHeaderEvent();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, this, map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        mQueue.add(requestParam);
    }

    private void processHeaderEvent() {
        mEventDetailAdapter.setEvent(event);
    }

    private void dealCardData(List<Card> templist) {
        if (page == 1) {
            mCardList.clear();
            mCardList.addAll(templist);
            mEventDetailAdapter.setType(mType);
            mEventDetailAdapter.notifyDataSetChanged();
        } else {
            int startPos = mCardList.size();
            mCardList.addAll(templist);
            mEventDetailAdapter.setType(mType);
            mEventDetailAdapter.notifyItemInserted(startPos + 1);
        }
    }

    @Override
    public void onBackClick() {
        finish();
    }

    @Override
    public void onActionClick(int id) {
        switch (id) {
            case R.id.base_action_bar_itemone:
                goShare();
                break;
        }
    }

    private void refreshData(String event_order) {
        this.event_order = event_order;
        if (!loading) {
            viewLoading.setVisibility(View.VISIBLE);
            end_flag = false;
            loading = true;
            page = 1;
            getHotData();
        }
    }

    private void goShare() {
        String url = "http://bcy.net/huodong/" + event_id;
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("content", String.format(getString(R.string.share_event), event.getTitle(), url));
        map.put("title", event.getTitle());
        map.put("url", url);
        map.put("imagePath", event.getCover());
        Intent intent = new Intent();
        intent.setClass(this, ShareActivity.class);
        intent.putExtra("showWarnBtn", false);
        intent.putExtra("map", map);
        startActivity(intent);
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    public void goPost() {
        if ("writer".equals(event.getType())) {
            judge(NovelApi.getVerifywriter());
        } else if ("coser".equals(event.getType())) {
            judge(CoserApi.getVerifycoser());
        } else if ("drawer".equals(event.getType())) {
            judge(IllustApi.getVerifydrawer());
        } else if ("daily".equals(event.getType())) {
            Intent intent = new Intent(this, WriteActivity.class);
            intent.putExtra("tag", event.getTag_name());
            startActivity(intent);
        }
    }

    private void judge(final String options) {
        viewLoading.setVisibility(View.VISIBLE);
        RuleHelper ruleHelper = new RuleHelper(this, new SimpleRuleImpl() {
            @Override
            public void judgeTrue(JSONObject result) {
                try {
                    JSONObject jsonObject = result.getJSONObject(HttpUtils.UPLOAD_DATA);
                    Gson gson = new Gson();
                    postRule = gson.fromJson(jsonObject.toString(), PostRule.class);
                    processData(options);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void judgeFalse(JSONObject result) {
                try {
                    viewLoading.setVisibility(View.GONE);
                    String data = result.getString(HttpUtils.UPLOAD_DATA);
                    MyToast.show(EventDetailActivity.this, data);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        ruleHelper.judge(options);
    }

    private void processData(String options) {
        viewLoading.setVisibility(View.GONE);
        if (CoserApi.getVerifycoser().equals(options))
            if (postRule.is_coser()) {
                postCos();
            } else {
                showRulesDialog(postRule.getRules(), CoserApi.getBecoser());
            }
        if (IllustApi.getVerifydrawer().equals(options))
            if (postRule.is_drawer()) {
                postDraw();
            } else {
                showRulesDialog(postRule.getRules(), IllustApi.getBedrawer());
            }
        if (NovelApi.getVerifywriter().equals(options))
            if (postRule.is_writer()) {
                postWrite();
            } else {
                showRulesDialog(postRule.getRules(), NovelApi.getBewriter());
            }
    }

    private void postCos() {
        gotoUtil.gotoAct(this, CosPostActivity.class, event.getTag_name());
    }

    private void postDraw() {
        gotoUtil.gotoAct(this, illustPostActivity.class, event.getTag_name());
    }

    private void postWrite() {
        showPostWriteDialog();
    }

    private void showRulesDialog(Rules rules, final String option) {
        RulesDialog.Builder builder = new RulesDialog.Builder(this, rules, true);
        rulesDialog = builder.setConfirmButton(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                verify(option);
            }
        }).create();
        if (!isFinishing())
            rulesDialog.show();
    }

    private void verify(final String options) {

        RuleHelper ruleHelper = new RuleHelper(this, new SimpleRuleImpl() {
            @Override
            public void changeSucc(JSONObject result) {
                if (null != rulesDialog && rulesDialog.isShowing())
                    rulesDialog.dismiss();
                if (CoserApi.getBecoser().equals(options))
                    postCos();
                if (IllustApi.getBedrawer().equals(options))
                    postDraw();
                if (NovelApi.getBewriter().equals(options))
                    postWrite();
            }

            @Override
            public void changeFail(JSONObject result) {
                try {
                    String data = result.getString(HttpUtils.UPLOAD_DATA);
                    MyToast.show(EventDetailActivity.this, data);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        ruleHelper.verify(options);
    }

    private void showPostWriteDialog() {
        PostWriteDialog.Builder builder = new PostWriteDialog.Builder(this);
        builder.setSingleWorkButton(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(EventDetailActivity.this, WriteArticleActivity.class);
                intent.putExtra("tags", event.getTag_name());
                startActivityForResult(intent, StartPostActivity.GO_WRITEARTICLE);
            }
        });
        builder.setSerialWorkButton(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(EventDetailActivity.this, SelectSeriesActivity.class);
                intent.putExtra("tags", event.getTag_name());
                startActivityForResult(intent, StartPostActivity.GO_SERIES);
            }
        });
        if (!isFinishing())
            builder.create().show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.view_sort_by_hot:
                if (null != mEventDetailAdapter)
                    mEventDetailAdapter.setHotIndicator();
                setHotIndicator();
                break;
            case R.id.view_sort_by_update:
                if (null != mEventDetailAdapter)
                    mEventDetailAdapter.setUpdateIndicator();
                setUpdateIndicator();
                break;
        }
    }

    public void setUpdateIndicator() {
        hotIndicator.setVisibility(View.GONE);
        updateIndicator.setVisibility(View.VISIBLE);
        tvUpdateTimeTips.setVisibility(View.INVISIBLE);
        jumpToTop();
        refreshData("index");
    }

    public void setHotIndicator() {
        hotIndicator.setVisibility(View.VISIBLE);
        updateIndicator.setVisibility(View.GONE);
        tvUpdateTimeTips.setVisibility(View.VISIBLE);
        jumpToTop();
        refreshData("hot");
    }

    private void jumpToTop() {
        if (viewTopIndicator.getVisibility() == View.VISIBLE) {
            viewTopIndicator.post(new Runnable() {
                @Override
                public void run() {
                    mGridLayoutManager.scrollToPositionWithOffset(2, UIUtils.dip2px(38, EventDetailActivity.this));
                }
            });
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }
}
